<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\common\model\CouponReceive;
use app\home\business\UserBusiness;
use think\facade\View;
use think\Request;

class Coupon extends Base
{
    /**
     * 优惠卷列表
     * @return string
     */
   public function list(){
       $data =  \app\common\model\Coupon::paginate(2);
       $receive_ids = [];
       $user_id = UserBusiness::getUserId();
       if ($user_id >0 ) {
           $receive_coupon = CouponReceive::where('buyer_id',$user_id)->select()->toArray();
           $receive_ids = array_column($receive_coupon,'coupon_id',NULL);
       }

       View::assign('data',$data);
       View::assign('receive_ids',$receive_ids);
       return View::fetch('coupon/list');
   }
   /**
    * 领取优惠卷
    */
   public function receive(){
       $id = \request()->get('id');//优惠卷id
       # 判断用户是否登录
       if (!session('?userInfo')) {
           # 保存一下回调的路由
           cookie('redirect_url','http://pyg.com/coupon');
           return  redirect('/login');//未登录、不能查看订单信息
       }

       $couponInfo = \app\common\model\Coupon::find($id);
       # 验证是否在领取时间范围
       if (strtotime($couponInfo['end_time']) < time()) {
           echo "优惠卷已超过领取时间";die();
       }
       # 添加数据 user_id
//       INSERT INTO `2002_pyg`.`pyg_coupon_receive`(`id`, `buyer_id`, `coupon_id`, `coupon_money`, `create_time`, `update_time`, `full_money`, `status`) VALUES (NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

       $data = [
           'buyer_id' => UserBusiness::getUserId(),
           'coupon_id' => $id,
           'coupon_money' => $couponInfo->used_amount,//优惠多少钱
           'full_money' => $couponInfo->with_amount,//满多少钱
           'status' => 0,
           'create_time' => time()
       ];

       $result = CouponReceive::create($data);
        if ($result) {
            return  redirect('/');
        }else {
            return  "领取失败";
        }
   }
}
